<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@page import="org.springframework.web.context.WebApplicationContext"%>
<%@page import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@page import="db.MsgDAO"%>
<%@page import="db.UserDAO"%>
<%@page import="db.User"%>
<%@page import="db.Msg"%>
<%@page import="db.Read"%>
<%@page import="db.ReadDAO"%>
<%@page import="db.AuthorityDAO"%>
<%@page import="db.Authority"%>
<%
	request.setCharacterEncoding("utf-8");

	if(session.getAttribute("id") == null){
		pageContext.forward("/index.jsp");
		return;
	}
	
	if(session.getAttribute("tid") == null){
		pageContext.forward("/vm/erp_tpl/welcome.html");
		return;
	}
%>
<%!
	public void submitMsg(int module1, int module2, String content, HttpSession session){
		WebApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		MsgDAO msgDao = (MsgDAO)ctx.getBean("MsgDAO");
		UserDAO userDao = (UserDAO)ctx.getBean("UserDAO");
		ReadDAO readDao = (ReadDAO)ctx.getBean("ReadDAO");
		AuthorityDAO authorityDao = (AuthorityDAO)ctx.getBean("AuthorityDAO");
		
		int tid = (Integer)session.getAttribute("tid");
		int uid = (Integer)session.getAttribute("id");
		
		User user = userDao.findById(uid);
	    
	    Msg msg = new Msg();
	    msg.setDate(new Date());
	    msg.setMsg(user.getName() + content);
	    msgDao.save(msg);
	    
	    List list = authorityDao.findByModule(new Object[]{module1,module2});
	    
	    if(list != null && list.size() > 0)
	    for(int i=0; i<list.size(); i++){
	    	Authority authority = (Authority)list.get(i);
	    	Read read = new Read();
		    read.setDate(new Date());
		    read.setMsgId(msg.getId());
		    read.setIsRead(0);
		    read.setTeamId(tid);
		    read.setUserId(authority.getUserId());
		    readDao.save(read);
	    }
	}
%>